//
//  UIViewController+Util.m
//  SWIOSLibary
//
//  Created by shaowei on 13-7-17.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "UIViewController+Util.h"

@implementation UIViewController (Util)

- (void)setRespondToHinddenKeyboard:(BOOL)enable{
    
    UITapGestureRecognizer *tapGesture = nil;
    
    for (UIGestureRecognizer *gesture in [self.view gestureRecognizers]) {
        if ([gesture isKindOfClass:[UITapGestureRecognizer class]]) {
            tapGesture = (UITapGestureRecognizer *)gesture;
        }
    }
    
    if (enable) {
        if (tapGesture) {
            tapGesture.enabled = YES;
        }else{
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                  action:@selector(hiddenKeyboard)];
            tap.delegate = self;
            [self.view addGestureRecognizer:tap];
        }
    }else{
        tapGesture.enabled = NO;
    }
    
    
}

- (void)hiddenKeyboard{
    [self.view endEditing:YES];
}

- (NSArray *)getTouchViewArray{
    //空方法，无实现
    return nil;
}

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isKindOfClass:[UIControl class]] || ![self checkTouch:touch]) {
        return NO;
    }else{
        DLog(@"SW -关闭键盘 touch.view:%@",NSStringFromClass([touch.view class]));
        return YES;
    }
    
}

- (BOOL)checkTouch:(UITouch *)touch{
    BOOL canResponse = YES;
    for (id touchObj in [self getTouchViewArray]) {
        if ([touchObj isKindOfClass:[UIView class]]) {
            //处理1，UIView对象
            UIView *subView = (UIView *)touchObj;
            CGRect mainRect = subView.frame;
            if (self.view != subView.superview) {
                //转换坐标系
                mainRect = [self.view convertRect:subView.frame fromView:subView.superview];
            }
            if (CGRectContainsPoint(mainRect, [touch locationInView:self.view])) {
                //touch 位于 禁止的隐藏事件的View内
                canResponse = NO;
                break;
            }
            
        }else if ([touchObj isKindOfClass:[NSString class]]){
            //处理2，NSString对象
            CGRect mainRect = CGRectFromString((NSString *)touchObj);
            if (CGRectContainsPoint(mainRect, [touch locationInView:self.view])) {
                //touch 位于 禁止的隐藏事件的Rect内
                canResponse = NO;
                break;
            }
        }else{
            DLog(@"SW - getTouchViewArray里面存在不兼容对象:%@",touchObj);
        }
    }
    return canResponse;
}



@end
